import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入一个home页，其他页面做懒加载
import Home from '@views/Home'
import { isLogin } from '@utils'
Vue.use(VueRouter)

const routes = [
  // 路由重定向 打开网页默认进入首页
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: '首页',
    component: Home,
    meta: {
      needLogin: false,
      keepAlive: true
    }
  },
  {
    path: '/cate',
    name: '分类',
    component: () => import('@views/Cate'), // 路由懒加载
    meta: {
      needLogin: false,
      keepAlive: true
    }
  },
  {
    path: '/cart',
    name: '购物车',
    component: () => import('@views/Cart'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/user',
    name: '个人中心',
    component: () => import('@views/User'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/itemLists',
    name: '商品列表',
    component: () => import('@views/ItemLists')
  },
  {
    path: '/itemDetail/:id',
    name: '商品详情',
    component: () => import('@views/Detail')
  },
  {
    path: '/register',
    name: '注册',
    component: () => import('@views/Register'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/login',
    name: '登录',
    component: () => import('@views/Login'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/contactList',
    name: '联系人列表',
    component: () => import('@views/ContactList'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactAdd',
    name: '增加联系人',
    component: () => import('@views/ContactAdd'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactEdit',
    name: '联系人列表',
    component: () => import('@views/ContactEdit'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/confirmOrder',
    name: '订单页',
    component: () => import('@views/ConfirmOrder'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/search',
    name: '搜索页',
    component: () => import('@views/Search'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/searchRedult',
    name: '搜索结果页',
    component: () => import('@views/SearchRedult'),
    meta: {
      needLogin: false
    }
  }
]

// 创建
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由的前置守卫 做登录鉴权
router.beforeEach((to, from, next) => {
  // 做判断进入这个路由要不要登录
  if (to.meta.needLogin) {
    // 需要登录 先判断有无token 有就放 没有就去登录页登录
    if (isLogin()) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  } else {
    // 不用登录 直接放行
    next()
  }
})
// 导出
export default router
